package com.bingo.bounce.sdk.utils;

import android.util.Base64;
import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;

import java.security.MessageDigest;

public class BBounceUtils {

    private static final String TRANSFORMATION = "AES/ECB/PKCS5Padding";
    private static final String ALGORITHM = "AES";
    private static final String CHARSET = "UTF-8";

    // 固定密钥（示例值，需替换）
    private static final String FIXED_KEY = "kkosd1d23Ew2d9sd";

    /**
     * 加密（相同明文输出相同密文）
     */
    public static String encrypt(String plainText) throws Exception {
        SecretKeySpec secretKey = generateKey(FIXED_KEY);

        Cipher cipher = Cipher.getInstance(TRANSFORMATION);
        cipher.init(Cipher.ENCRYPT_MODE, secretKey);
        byte[] encryptedBytes = cipher.doFinal(plainText.getBytes(CHARSET));

        return Base64.encodeToString(encryptedBytes, Base64.NO_WRAP);
    }

    /**
     * 解密
     */
    public static String decrypt(String encryptedText) {

        try {
            SecretKeySpec secretKey = generateKey(FIXED_KEY);

            Cipher cipher = Cipher.getInstance(TRANSFORMATION);
            cipher.init(Cipher.DECRYPT_MODE, secretKey);
            byte[] decryptedBytes = cipher.doFinal(Base64.decode(encryptedText, Base64.NO_WRAP));

            return new String(decryptedBytes, CHARSET);
        }catch (Exception e){
            e.printStackTrace();
        }
        return "";
    }

    /**
     * 生成固定密钥
     */
    private static SecretKeySpec generateKey(String key) throws Exception {
        MessageDigest digest = MessageDigest.getInstance("SHA-256");
        byte[] hash = digest.digest(key.getBytes(CHARSET));
        return new SecretKeySpec(hash, ALGORITHM); // 自动截取前256位
    }
}
